package main

import (
	"errors"
	"fmt"
	"github.com/afex/hystrix-go/hystrix"
	"math/rand"
	"sync"
	"time"
)

func main() {

	configA := hystrix.CommandConfig{
		Timeout:               2000,
		MaxConcurrentRequests: 3,
	}

	hystrix.ConfigureCommand("get_prod", configA)

	intChan := make(chan int, 1)

	wg := sync.WaitGroup{}
	wg.Add(10)
	for i := 0; i < 10; i++ {
		go func() {
			defer wg.Done()
			errs := hystrix.Go("get_prod", func() error {
				p := getProduct()
				//fmt.Println(p)
				intChan <- p
				return nil
			}, func(err error) error {
				fmt.Println("callback")
				//intChan <- 9999
				return errors.New("time out")
			})
			select {
			case product := <-intChan:
				fmt.Println(product)
			case err := <-errs:
				fmt.Println(err)

			}
		}()
	}
	wg.Wait()
	/*for true {
		errs := hystrix.Go("get_prod", func() error {
			p := getProduct()
			//fmt.Println(p)
			intChan <- p
			return nil
		}, func(err error) error {
			fmt.Println("callback")
			//intChan <- 9999
			return errors.New("time out")
		})
		select {
		case product := <-intChan:
			fmt.Println(product)
		case err:= <- errs:
			fmt.Println(err)

		}
	}*/

}

func getProduct() int {

	r := rand.Intn(10)
	if r < 6 {
		time.Sleep(time.Second * 4)
	}
	return r
}
